<template>
  <div class="pages auditrecords">
    <div class="pageLevel">
      <!-- 搜索框 -->
      <div class="tableSearch">
        <el-form label-width="90px" class="demo-ruleForm">
          <el-form-item label label-width="15">
            <el-input
              placeholder="请输入商品名称搜索"
              v-model="clientsalePrice.shopName"
              size="small"
              style="width:200px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品品牌:" label-width="100px">
            <el-select
              size="small"
              filterable
              style="width:190px"
              v-model="clientsalePrice.brandId"
              placeholder="请先选择商品品牌"
            >
              <el-option label="全部" value></el-option>
              <el-option
                v-for="(item,index) in commodityBrandList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户类型:" prop="shopTypeIds" class="shop-type-wrap">
            <el-select
              v-model="clientsalePrice.shopTypeIds"
              placeholder="请选择"
              size="small"
              style="width:190px"
            >
              <el-option label="全部" value></el-option>
              <el-option
                v-for="item in shopTypesList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态:" prop="auditsStatus" class="shop-type-wrap">
            <el-select
              v-model="clientsalePrice.auditsStatus"
              placeholder="请选择"
              size="small"
              style="width:190px"
            >
              <el-option
                v-for="item in auditsStatussList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label label-width="20px">
            <el-button type="primary" size="mini" @click="counsearch" class="Button">查询</el-button>
          </el-form-item>
          <el-form-item label label-width="20px">
            <el-button type="primary" size="mini"  @click="goBack()">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 批量审核 -->
      <!-- 批量通过 -->
      <div style="margin-bottom:20px;">
        <el-button type="primary" size="mini" v-if="setRole('审核')" @click="_batchpass(1)">批量通过</el-button>
        <el-button type="primary" size="mini" v-if="setRole('审核')" @click="_batchpass(2)">批量驳回</el-button>
      </div>
    
      <!-- 表格 -->
      <div class="tableMain">
        <el-table
          ref="multipleTable"
          :data="pricemange.tableData"
          @selection-change="pricemange.handleMultipleSelect"
          :row-key="getRowKeys"
          stripe
          style="width: 100%"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
            :selectable="puStatus"
          ></el-table-column>
          <el-table-column prop="barCode" fixed width="120" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="primaryClassifyName" label="分类" align="center"></el-table-column>
          <el-table-column prop="goodsLabelName" label="商品品牌" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null">{{item.paramValue}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsUnit" label="单位" align="center"></el-table-column>
          <el-table-column prop="shopTypeName" label="客户类型" align="center"></el-table-column>
          <el-table-column prop="price" label="期间价格" align="center"></el-table-column>
          <el-table-column prop="entryTime" label="价格生效日期" align="center" width="200">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.entryTime" :key="index">
                <span>{{item.startDate}}</span>-
                <span>{{item.endDate}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.auditRemark"
                placement="top"
              >
                <div>{{auditStatuslist[scope.row.auditStatus]}}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="creater" label="申请人" align="center"></el-table-column>
          <el-table-column prop="createTime" :formatter="tim" label="添加日期" align="center"></el-table-column>
          <el-table-column prop="name" align="center" label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="small"
                @click="_priceadopt(scope.$index,scope.row)"
                type="text"
                class="addDetail"
                v-if="scope.row.auditStatus=='0'&&setRole('审核')"
              >通过</el-button>
              <el-button
                size="small"
                @click="rejectDialog.dialog=true,_pricereject(scope.$index,scope.row)"
                type="text"
                class="addDetail"
                v-if="scope.row.auditStatus=='0'&&setRole('审核')"
              >驳回</el-button>
              <el-button
                size="small"
                @click="_priceedit(scope.$index,scope.row)"
                type="text"
                v-if="scope.row.auditStatus=='2'"
                class="addDetail"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <page-unit :pageData="pricemange.pageData" :func="_pricemangeListPage"></page-unit>
      </div>
    </div>
    <!-- 修改调价开始 -->
    <el-dialog
      width="35%"
      title="修改调价"
      :visible.sync="addprice.dialog"
      append-to-body
      class="addshopname"
    >
      <i class="el-icon-close icon" @click="resetForm('ruleForm')"></i>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="生效期间：" prop="effectiveperiod">
          <el-date-picker
           :clearable="false"
            size="small"
            v-model="ruleForm.effectiveperiod"
            format="yyyy年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="期间价格：" prop="interimprice">
          <el-input v-model="ruleForm.interimprice" size="small"></el-input>
          <span>元</span>
        </el-form-item>
        <el-form-item label="调价原因：" prop="pricereason">
          <textarea
            maxlength="20"
            v-model="ruleForm.pricereason"
            name
            id
            cols="10"
            rows="5"
            style="width:220px;resize:none;border-radius:5px;"
          ></textarea>
        </el-form-item>
        <!-- <span>注：若审核日期在生效日期内，则期间价格在下一个自然日开始时生效</span> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :disabled="submin" size="small">提 交</el-button>
      </div>
    </el-dialog>
    <!-- 新增调价结束 -->

    <!-- 驳回 弹窗-->
    <el-dialog
      title="确认驳回此条价格调整审核吗？"
      :visible.sync="rejectDialog.dialog"
      :closeOnClickModal="false"
      :closeOnPressEscape="false"
      width="25%"
    >
      <div style="margin-left:20px;font-size:16px;
      margin-bottom:20px;">
        <span>驳回原因</span>
      </div>
      <textarea
        onkeyup="this.value=this.value.replace(/^ +| +$/g,'')"
        v-model="dismissal"
        placeholder
        name
        id
        cols="7"
        rows="5"
        maxlength="20"
        style="width:280px;resize:none;margin-left:20px;"
      ></textarea>
      <div style="text-align:center">
        <el-button size="small" style="margin-top: 12px;" @click="rejectDialog.dialog=false">取消</el-button>
        <el-button size="small" type="primary" @click="confirmRejected">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import util from "@/util";
import u from "@/util/state";
import { TableHandle } from "@/util/class";
import pageUnit from "components/Page";
import {
  getGoodsLabelListByShopId,
  selectShopTypeList,
  listUpdateStatus,
  listAuditPrice,
  updateStatuspri,
  saveUpdatePrice
} from "@/api";
export default {
  computed: mapState(["sub", "merchantId", "power", "linkName", "mobile"]),
  components: { pageUnit },
  data() {
    return {
      getRowKeys(row) {
        return row.detailId; // 获取row的key值
      },
      agreementStatusList: u.agreementStatusList,
      agreementTypeList: u.agreementTypeList,
      commodityBrandList: [], // 商品品牌
      shopTypesList: [], //客户名称
      clientsalePrice: {
        shopName: "",
        brandId: "",
        shopTypeIds: "",
        auditsStatus: ""
      },
      isshow: false, //是否可修改
      update: true, //批量更新按钮
      sumber: false, //保存按钮
      // 调价历史外弹窗
      pricemange: new TableHandle(), //统一价格
      addprice: new TableHandle(), //修改调价
      rejectDialog: new TableHandle(), //驳回价格协议
      auditsStatussList: [
        {
          id: "",
          name: "全部"
        },
        {
          id: "0",
          name: "未审核"
        },
        {
          id: "1",
          name: "审核通过"
        },
        {
          id: "2",
          name: "审核驳回"
        }
      ],

      // 新增调价
      rules: {
        effectiveperiod: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        interimprice: [
          { required: true, message: "请输入期间价格", trigger: "blur" },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          }
        ],
        pricereason: [
          { required: true, message: "请输入调价原因", trigger: "blur" }
        ]
      },
      ruleForm: {
        effectiveperiod: [],
        interimprice: "",
        pricereason: ""
      },
      dismissal: "", //驳回原因
      auditStatuslist: ["未审核", "审核通过", "审核驳回"], //审核价格列表
      rejectId: "", //驳回id
      arrpriId: [], //批量选择的id
      editpriceId: "", //修改id
      auditStatus: "",//审核状态
      users: "",
      submin: false
    };
  },
  mounted() {
    this.name = util.getQuery().name;
    this.customerId = util.getQuery().id;
    this._pricemangeListPage(this.pricemange.pageData.pageSize, this.pricemange.pageData.currentPage);
    this.commodityBrand();
    this.getShopTypeList();
    this.init()
  },
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this._pricemangeListPage(this.pricemange.pageData.pageSize, this.pricemange.pageData.currentPage);
        }
      },
      deep: true
    }
  },
  methods: {
    init() {
      if (this.linkName == undefined || this.linkName == "") {
        this.users = this.mobile;
      } else {
        this.users = this.linkName;
      }
    },
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    // 商品品牌
    commodityBrand() {
      getGoodsLabelListByShopId({
        labelType: "0",
        shopId: this.merchantId
      }).then(res => {
        this.commodityBrandList = res.data.list;
      });
    },
    // 客户类型
    getShopTypeList() {
      let data = {
        shopId: this.merchantId,
        name: "",
        status: 0
      };
      selectShopTypeList(data).then(res => {
        if (res.code == 200) {
          this.shopTypesList = res.data;
        }
      });
    },
    // 调价审核记录列表
    _pricemangeListPage(pageSize, pageNum) {
      let data = {
        pageNum: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId,
        goodsName: this.clientsalePrice.shopName,
        goodsLabelId: this.clientsalePrice.brandId,
        shopTypeId: this.clientsalePrice.shopTypeIds,
        auditStatus: this.clientsalePrice.auditsStatus
      };
      listAuditPrice(data).then(res => {
        this.pricemange.tableData = res.data.list;
        this.pricemange.tableData.forEach(ele => {
          ele.entryTime = [];
          ele.timobj = {};
          ele.timobj.startDate = util.foryear(ele.startDate);
          ele.timobj.endDate = util.foryear(ele.endDate);
          ele.entryTime.push(ele.timobj);
        });
        this.pricemange.pageData.totalItems = res.data.pageTotal;
      });
    },
    // 查询按钮
    counsearch() {
      this._pricemangeListPage(this.pricemange.pageData.pageSize, this.pricemange.pageData.currentPage);
    },
    // 返回按钮
    goBack () {
      history.back();
    },
    // 保存
    _preservation() {
      this.isshow = false;
      this.sumber = false;
      this.update = true;
    },
    //转时间戳
    tim(row, column) {
      return util.foryear(row.createTime);
    },
    // 通过
    _priceadopt(index, rows, type) {
      this.$confirm("确认通过此条价格调整审核吗？", "", {
        center: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      })
        .then(() => {
          this._UpdateStatulist(rows.detailId, 1, "");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消审核"
          });
        });
    },
    // 驳回
    _pricereject(index, rows) {
      this.rejectId = rows.detailId;
      this.dismissal=""

    },
    // 驳回提交
    confirmRejected() {
      if (this.dismissal == "") {
        this.$message({
          type: "error",
          message: "请填写驳回原因!"
        });
      } else {
        this._UpdateStatulist(this.rejectId, 2, this.dismissal);
      }
    },
    // 审核通过驳回状态接口
    _UpdateStatulist(id, type, name) {
      let data = {
        detailId: id,
        auditStatus: type,
        auditRemark: name
      };
      updateStatuspri(data).then(res => {
        if (res.code == "200") {
          this._pricemangeListPage(this.pricemange.pageData.pageSize, this.pricemange.pageData.currentPage);
          this.rejectDialog.dialog = false;
          this.$message({
            type: "success",
            message: res.msg
          });
        }
      });
    },
    // 批量审核通过驳回状态接口
    _listUpdateStatulist(id, type) {
      let data = {
        detailId: id,
        auditStatus: type
      };
      let self = this;
      listUpdateStatus(data).then(res => {
        if (res.code == "200") {
          self._pricemangeListPage(this.pricemange.pageData.pageSize, this.pricemange.pageData.currentPage);
          this.$message({
            type: "success",
            message: res.msg
          });
          this.$refs.multipleTable.clearSelection()
        }
      });
    },
    //批量通过驳回
    _batchpass(type) {
      let that = this;
      let a = [];
      if (this.pricemange.isSelect(2, this, "请先选择调价记录！")) {
        this.pricemange.multipleSelectTable.forEach(item => {
          a.push(item.detailId);
          that.arrpriId = a.toString();
        });
        this._listUpdateStatulist(that.arrpriId, type);
      }
    },
    puStatus(row) {
      return row.auditStatus == 0;
    },

    // 调价历史
    _pricehistory(index, rows) {
      // this.orderTable.dialog = true;
    },
    // 修改价格
    _priceedit(index, rows) {
      this.addprice.dialog=true
      this.editpriceId = rows.detailId;
      this.auditStatus = rows.auditStatus;
      let a=util.foryear(rows.startDate);
      let b=util.foryear(rows.endDate);
      // this.ruleForm.effectiveperiod[0] =a;
      // this.$set(this.ruleForm,"effectiveperiod[0]",util.foryear(rows.startDate))
      // this.$set(this.ruleForm,"effectiveperiod[1]",util.foryear(rows.endDate))
      // this.ruleForm.effectiveperiod[1] = b;
      this.ruleForm.effectiveperiod.push(a)
      this.ruleForm.effectiveperiod.push(b)
      this.ruleForm.interimprice = rows.price;
      this.ruleForm.pricereason = rows.auditRemark;
      console.log(this.ruleForm)
    },
    // 修改调价保存
    submitForm(formName) {
       this.submin = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          saveUpdatePrice({
            detailId: this.editpriceId,
            auditStatus: "0",
            price: this.ruleForm.interimprice,
            startDate: this.ruleForm.effectiveperiod[0],
            endDate: this.ruleForm.effectiveperiod[1],
            remark: this.ruleForm.pricereason,
            creater: this.users
          }).then(res => {
            this.submin = false;
            this.ruleForm.effectiveperiod=[]
            if (res.code == "200") {
              this.addprice.dialog = false;
              this._pricemangeListPage(this.pricemange.pageData.pageSize, this.pricemange.pageData.currentPage);
            }
          });
          // alert("submit!");
        } else {
          this.submin = false;
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm.effectiveperiod=[]
      this.addprice.dialog = false;
    }
  }
};
</script>
<style>
.billdata .el-date-editor .el-range__close-icon {
  display: none;
}
</style>
